package com.example.datasource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.junit.Test;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.util.Properties;

public class DBCPTest {

    // 方式一：硬编码数据库配置信息
    @Test
    public void testGetConnection() throws Exception {
        // 创建dbcp连接池
        BasicDataSource basicDataSource = new BasicDataSource();
        // 设置属性
        basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        basicDataSource.setUrl("jdbc:mysql://60.60.60.223:30335/test?rewriteBatchedStatements=true");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("admin1#3");
        // 设置初始时池中连接数
        basicDataSource.setInitialSize(10);
        basicDataSource.setMaxTotal(20);

        // 获取连接
        Connection connection = basicDataSource.getConnection();
        System.out.println(connection);
    }

    // 方式二：使用配置文件
    @Test
    public void testGetConnection1() throws Exception {
        // 创建dbcp连接池
        Properties properties = new Properties();
        properties.load(Files.newInputStream(Paths.get("src/main/resources", "dbcp.properties")));
        BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties);

        // 获取连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

}
